package org.yumeko.cmdb.main;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class CmdbClient {
//    - mysql_instance
//    - mysql_service
//    - mysql_user
//    - oracle_instance
//    - oracle_service
//    - oracle_user
//    - otherDB_instance
//    - otherDB_service
//    - otherDB_user
//    - panwei_instance
//    - panwei_service
//    - panwei_user
//    - oceanbase_instance
//    - oceanbase_service
//    - oceanbase_user
// rw_access_address 读写地址
// ro_access_address只读地址
// rw_access_domain_name 读写域名
// ro_access_domain_name 只读域名

    private static final String HOST = "http://cmdb.cloud.cmft:8081"; //http://10.176.31.132:8081
    private static final String SECRET = "18a6413dc4fe394c66345ebe501b2f26";

    public static void main(String[] args) {
        // API的参数
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("model_name", "panwei_service");
//        apiParams.put("relation", true);
        apiParams.put("page", 1);
        apiParams.put("pageSize", 1);

        Map<String, Object> params = new HashMap<>();

        // 对“接口应用请求数据”进行整体json序列化，得到一个新的参数data
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String dataJson = objectMapper.writeValueAsString(apiParams);
            params.put("data", dataJson);
            params.put("timestamp", System.currentTimeMillis() / 1000);

            System.out.println("生成的参数: " + params);

            // secret + 参数进行连接，得到加密前的字符串
            String hashStr = String.format("%sdata%stimestamp%d", SECRET, dataJson, params.get("timestamp"));
            System.out.println("加密前的字符串: " + hashStr);

            // 对上述字符串进行sha1算法加密
            String sign = DigestUtils.sha1Hex(hashStr);
            params.put("sign", sign);

            System.out.println("生成的参数: " + params);

            // 请求“资产列表API”
            String url = HOST + "/api/v6/cmdb/instances";
            System.out.println("访问地址: " + url);

            // 使用 json 参数发送 JSON 格式的请求体
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                Map<String, Object> insts = objectMapper.readValue(responseBody, Map.class);

                if ((int) insts.get("code") != 0) {
                    System.out.println("查询失败，错误信息：" + insts.get("message"));
                    System.exit(1);
                }

                JsonNode dataNode = objectMapper.readTree(responseBody).get("data");
                JsonNode rowsNode = dataNode.get("rows");
                System.out.println("响应体: " + rowsNode);
            } else {
                System.out.println("请求失败，状态码：" + response.getStatusCode());
                System.exit(1);
            }
        } catch (Exception e) {
            System.out.println("请求异常: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
    private void processData(JsonNode dataRows, String modelName) {
        Optional.ofNullable(modelName)
                .map(String::trim)
                .map(name -> name.toLowerCase())
                .map(name -> name.contains("_") ? name.substring(name.lastIndexOf('_') + 1) : name)
                .ifPresent(name -> {
                    switch (name) {
                        case "instance":
                            insertIntoInstance(dataRows, modelName);
                            break;
                        case "service":
                            insertIntoService(dataRows, modelName);
                            break;
                        case "user":
                            insertIntoUser(dataRows, modelName);
                            break;
                        default:
                            break;
                    }
                });
    }

    private void insertIntoUser(JsonNode dataRows, String modelName) {
        System.out.println("进来了");
    }

    private void insertIntoService(JsonNode dataRows, String modelName) {
        System.out.println("进来了");
    }

    private void insertIntoInstance(JsonNode dataRows, String modelName) {
        System.out.println("进来了");
    }
}
